// pages/myOrders/myOrders.js
import {
  update_scan,
  unified_order,
  unified_order_v4,
  get_carte_count,
  get_open_id,
  user_login,
  get_carte
} from "../../utils/api.js";
import {
  MD5
} from '../../utils/MD5.js'
const app = getApp()
var page = 1;
var selectedNews = false;
var newsList = [];

Page({

  /**
   * 页面的初始数据
   */
  data: {
    haveTap: 1, // 1: 可以点击 0：不可点击
    goodsList: [],
    SwitchTabList: [{
        id: 0,
        title: '全部',
      },
      {
        id: 1,
        title: '待付款',
      },
      {
        id: 2,
        title: '待发货',
      },
      {
        id: 3,
        title: '待收货',
      },
      {
        id: 6,
        title: '退换售后',
      },
      {
        id: 4,
        title: '待评价',
      }
    ],
    SwitchSelect: 0,
    TaskShow: 0,
    loading:true
  },
  // 点击进入个人名片页面
  bindMyCarte: function(e) {
    wx.navigateTo({
      url: '../myCarte/myCarte',
    })
  },
  showExpress: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/shopPages/express/express?id=' + id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.ordertype == "待付款") {
      this.setData({
        SwitchSelect: 1
      })
    } else if (options.ordertype == "待发货") {
      this.setData({
        SwitchSelect: 2
      })
    } else if (options.ordertype == "待收货") {
      this.setData({
        SwitchSelect: 3
      })
    } else if (options.ordertype == "退换售后") {
      this.setData({
        SwitchSelect: 6
      })
    }
    page = 1;
    selectedNews = false;
    newsList = [];
    this.getOrdersList(this.data.SwitchSelect);

    if (options.share_id && options.carte_id) {
      app.globalData.shareOptions.share_id = options.share_id;
      app.globalData.shareOptions.carte_id = options.carte_id;
      app.globalData.SwitchTabParams.v_id = options.carte_id;
    }
    this.checkUserInfo()
  },

  // 检测是否需要登录
  checkUserInfo: function() {
    const that = this
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },
        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                haveTap: 1,
                userInfo: result_data.data
              })
            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function(result) {
                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                    }
                  })
                }
              })
            }
          }
        })
    } else {
      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function(result) {
            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.openid = result.data.openid.openid;
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                openid: result.data.openid.openid
              })
              that.setData({
                TaskShow: 1,
                openid: result.data.openid.openid
              })
            }
          })
        }
      })
    }
  },

  // 获取用户信息
  bindGetUserInfo: function(e) {
    const that = this
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: that.data.openid,
          username: userInfo.nickName,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender
        },
        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              TaskShow: 0,
              haveTap: 1,
              userInfo: userInfo
            })
          }
        })
    } catch (error) {

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // page = 1;
    // this.getOrdersList(this.data.SwitchSelect)
    this.setData({
      loading:true
    })
  },
  //点击提醒发货
  tishiSent: function(e) {
    var id = e.currentTarget.dataset.id;
    var order_group_id = e.currentTarget.dataset.order_group_id;
    var mgid = e.currentTarget.dataset.mgid;
    app.showTipMsg('已提醒!');
    // 发送模板消息-访客到访通知
    app.sendTemplateMessage(e.currentTarget.dataset.mg_uid, 9, '', '', order_group_id, '', '', mgid);
  },
  //点击查看订单详情
  showOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?id=' + id,
    })
  },
  //点击付款
  payOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    var price = e.currentTarget.dataset.price;
    var freight_free = e.currentTarget.dataset.freight_free;
    var integral_price = e.currentTarget.dataset.integral_price;
    var mgid = e.currentTarget.dataset.mgid;
    var sn = e.currentTarget.dataset.sn;
    let params = {
      total_fee: price * 100,
      openid: app.globalData.openid,
      order_id: id + '',
      body: sn,
      type: 1,
      order_source: 1,
      timestamp: new Date().getTime(),
    }
    params.sign = app.getSign(params)
    console.log(params)
    try {
      app.HttpPostSend(unified_order_v4, params, function(unified_order_res) {
        if (unified_order_res.msg != "success") {
          wx.showModal({
            title: '提示',
            content: unified_order_res.msg,
            showCancel: false,
            success:function(){
              wx.switchTab({
                url: '/pages/shop/shop',
              })
            }
          })
        } else {
          // console.log(unified_order_res)
          if (Number(unified_order_res.code) == 1) {
            // let order_arr = unified_order_res.data.order_arr
            // 数据结构改变 let order_arr = unified_order_res.data
            let order_arr = unified_order_res.data
            if (unified_order_res.data.order_arr != undefined) {
              order_arr = unified_order_res.data.order_arr
            }
            let signA = "appId=" + order_arr.appid + "&nonceStr=" + order_arr.noncestr + "&package=prepay_id=" + order_arr.prepayid + "&signType=MD5&timeStamp=" + order_arr.timestamp;
            let signB = signA + "&key=" + unified_order_res.data.key
            let new_pay_sign = MD5(signB)
            // console.log(new_pay_sign)
            wx.requestPayment({
              timeStamp: order_arr.timestamp,
              nonceStr: order_arr.noncestr,
              package: 'prepay_id=' + order_arr.prepayid,
              signType: 'MD5',
              profit_sharing: 'Y',
              paySign: new_pay_sign,
              success(pay_res) {
                // console.log(pay_res)
                var url2 = '/order/updateOrderStatus_v4';
                var params2 = {
                  id: id,
                  type: 2,
                  invite_id: app.globalData.shareOptions.share_id,
                  invite_uid: app.globalData.shareOptions.carte_id,
                  timestamp: new Date().getTime(),
                };
                params2.sign = app.getSign(params2)
                app.HttpPostSend(url2, params2, function(res) {
                  if (res.msg != "success") {
                    app.showTipMsg(res.msg);
                  } else {

                    // 雷达添加查看记录 -商品付款成功数
                    app.radarAdd(e.currentTarget.dataset.mg_uid, 19, 0, price, app.globalData.userInfo.logo)
                    app.addlog(e.currentTarget.dataset.mg_uid,'', app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 19, '')
                    // 发送模板消息-访客到访通知
                    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '付款成功', '', '', '')

                    // 发送模板消息-访客到访通知
                    console.log(sn);
                    app.sendTemplateMessage(e.currentTarget.dataset.mg_uid, 10, '/shopPages/houOrderDetail/houOrderDetail?id=' + id, '', sn, '', '', mgid);

                    wx.redirectTo({
                      url: '/shopPages/orderSuccess/orderSuccess?price=' + price + '&id=' + id + '&integral=' + JSON.stringify(integral_price) + '&freight_free=' + freight_free
                    })
                  }
                });
              },
              fail(err_res) {
                // console.log(err_res)
                // wx.redirectTo({
                //   url: '/pages/myOrders/myOrders',
                // })
              }
            })
          } else {
            app.showTipMsg(res.msg);
          }
          // wx.navigateTo({
          //   url: '/pages/paySuccess/paySuccess?price=' + that.data.sumprice + '&id=' + res.data
          // })
        }
      })
    } catch (error) {
      console.log(error)
    }

  },
  //点击取消订单
  cancelOrder: function(e) {
    const that = this
    
    wx.showModal({
      title: '提示',
      content: '请确认取消订单',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 0,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              // console.log('>>>>>>>' + e.currentTarget.dataset.mg_uid)
              // 雷达添加查看记录 -取消订单数
              app.radarAdd(e.currentTarget.dataset.mg_uid, 20, '', '', app.globalData.userInfo.logo)
              app.addlog(e.currentTarget.dataset.mg_uid,'', app.globalData.userInfo.id, app.globalData.userInfo.username,app.globalData.userInfo.logo, 20, '')
              // 发送模板消息-访客到访通知
              // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '取消了订单', '', '', '')

              page = 1;
              selectedNews = false;
              newsList = [];
              that.getOrdersList(that.data.SwitchSelect);
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
  //点击确认收货
  sureGet: function(e) {
    const that = this
    wx.showModal({
      title: '提示',
      content: '请确认收货',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '收货中',
          })
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 4,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            wx.hideLoading();
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {

              // 发送模板消息-确认收货通知
              // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 6, '/radarPages/radarCenter/radarCenter', id, '', '', '')

              page = 1;
              selectedNews = false;
              newsList = [];
              that.setData({
                SwitchSelect: 0
              })
              that.getOrdersList(that.data.SwitchSelect);
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //点击去评价
  pingjOrder: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../shopPages/Publication/Publication?order_id=' + id,
    })
  },
  //点击删除订单
  deleteOrder: function(e) {
    const that = this
    wx.showModal({
      title: '提示',
      content: '请确认删除订单',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 7,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              page = 1;
              selectedNews = false;
              newsList = [];
              that.setData({
                SwitchSelect: 0
              })
              that.getOrdersList(that.data.SwitchSelect);
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  //点击申请售后
  applyGoods: function(e) {

    wx.showModal({
      title: '提示',
      content: '请确认该订单申请售后',
      success(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.id;
          var url2 = '/order/updateOrderStatus_v4';
          var params2 = {
            id: id,
            type: 6,
            invite_id: app.globalData.shareOptions.share_id,
            invite_uid: app.globalData.shareOptions.carte_id,
            timestamp: new Date().getTime(),
          };
          params2.sign = app.getSign(params2)
          app.HttpPostSend(url2, params2, function(res) {
            if (res.msg != "success") {
              wx.showToast({
                title: '申请失败',
                icon: 'none',
                duration: 1000
              })
            } else {
              app.showTipMsg('申请成功');
              // this.getOrdersList(0);
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  // 获取我的订单列表
  getOrdersList: function(switchSelect) {
    const that = this
    var url2 = '/order/index';
    let params = {
      uid: app.globalData.userInfo.id,
      type: switchSelect,
      page: page
    };
    wx.showLoading({title: '获取订单中'})
    app.HttpGetSend(url2, params, function(res) {
      wx.hideLoading();
      wx.hideNavigationBarLoading();//隐藏导航条加载动画。

      wx.stopPullDownRefresh();//停止当前页面下拉刷新。
      that.setData({
        loading:false
      })
      
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
        selectedNews = false;
        that.setData({
          goodsList: []
        })
      } else {
        if (page == 1) {
          newsList = [];
        }

        for (let i in res.data) {
          var obj = {};
          obj = res.data[i];
          var goods_list = res.data[i].goods_info;
          var goodsSum = 0;
          var goodsNum = 0;
          for (let j = 0; j < goods_list.length; j++) {
            goods_list[j].title = goods_list[j].title.substr(0, 12);
            goodsSum += goods_list[j].num * goods_list[j].price;
            goodsNum += Number(goods_list[j].num);
          }
          obj.goodsSum = goodsSum;
          obj.goodsNum = Number(goodsNum);
          obj.checked = false;
          // lists.push(obj);
          newsList.push(obj);
        }
        if (res.data.length < 10) {
          selectedNews = false;
        } else {
          selectedNews = true;
          page += 1;
        }
        that.setData({
          goodsList: newsList
        })
        wx.hideLoading();
      }
    })
  },

  // 头部 Tab 切换
  switchList: function(e) {
    page = 1;
    selectedNews = false;
    newsList = [];
    this.setData({
      goodsList: [],
      SwitchSelect: e.currentTarget.dataset.id,
      loading:true
    })
    this.getOrdersList(e.currentTarget.dataset.id)

  },

  // 进入名片详情页
  showCarte: function(e) {
    const that = this
    const haveTap = this.data.haveTap
    if (haveTap == 0) {
      console.log('屏蔽重复点击')
    } else {
      that.setData({
        haveTap: 0
      })
      app.HttpGetSend(
        update_scan, {
          uid: e.currentTarget.dataset.id,
          browse_id: app.globalData.userInfo.id
        },
        function(res) {
          if (res.msg != "success") {
            app.showTipMsg(res.msg);
          } else {
            app.globalData.SwitchTabParams = {
              v_id: e.currentTarget.dataset.id
            }
            that.setData({
              haveTap: 1
            })
            wx.switchTab({
              url: '/pages/carteShow/carteShow'
            })
          }
        })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    page = 1;
    wx.showNavigationBarLoading();//在当前页面显示导航条加载动画。
    this.getOrdersList(this.data.SwitchSelect)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (selectedNews == true) {
      var that = this;
      // 显示加载图标  
      wx.showLoading({
        title: '玩命加载中',
      })
      // 页数+1  
      that.getOrdersList(that.data.SwitchSelect);

    } else {
      wx.hideLoading();
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function(e) {

  // }
})